package com.wbt.bambootown.receiver;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.wbt.bambootown.cons.Cons;
import com.wbt.bambootown.entity.SignalR;
import com.wbt.bambootown.utils.EventCenter;

import org.greenrobot.eventbus.EventBus;

import microsoft.aspnet.signalr.client.Action;
import microsoft.aspnet.signalr.client.ErrorCallback;
import microsoft.aspnet.signalr.client.LogLevel;
import microsoft.aspnet.signalr.client.Logger;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.Subscription;

/**
 * Created by wufan on 2018/5/23.
 */

public class SignalRService extends Service {
    private HubConnection mHubConnection;
    private HubProxy mHubProxy;
    private final LocalBinder mBinder = new LocalBinder();
    public Boolean is_service_connected = false;
    private Context context;
    private Gson gson = new Gson();

    public SignalRService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getBaseContext();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int result = super.onStartCommand(intent, flags, startId);
        startSignalR();
        return result;
    }

    @Override
    public void onDestroy() {
        mHubConnection.stop();
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        startSignalR();
        return (IBinder) mBinder;
    }

    public class LocalBinder extends Binder {
        public SignalRService getService() {
            // Return this instance of SignalRService so clients can call public methods
            return SignalRService.this;
        }
    }

    public void sendToWindowsServer(int controlDeviceId, int cmdType) {
        mHubProxy.invoke("sendToWindowsServer", mHubConnection.getConnectionId(), controlDeviceId + "", cmdType + "", "App");
    }

    public void startSignalR() {
        Logger logger = new Logger() {
            @Override
            public void log(String message, LogLevel level) {
                Log.e("SignalRService", "log:" + message);
            }
        };
        // Connect to the server
        mHubConnection = new HubConnection("http://service.smartiot.cc:1183/", "", true, logger);

        // Create the hub proxy
        mHubProxy = mHubConnection.createHubProxy("serverHub");

        Subscription subscription = mHubProxy.subscribe("sendMessageToClient");
        subscription.addReceivedHandler(new Action<JsonElement[]>() {
            @Override
            public void run(JsonElement[] jsonElements) throws Exception {
                String json = jsonElements[0].getAsString();
                SignalR signalR = gson.fromJson(json, SignalR.class);
                Log.e("Tag" , signalR.toString());
                if(null != signalR.getData().getSuccess() && !TextUtils.isEmpty(signalR.getData().getSuccess())){
                    if(signalR.getData().getSuccess().equals("1")){
                        //控制成功
                        EventBus.getDefault().post(new EventCenter<>(Cons.DevicesControl.DEVICES_CONTROL_SUCCESS));
                    }else{
                        //控制失败
                        EventBus.getDefault().post(new EventCenter<>(Cons.DevicesControl.DEVICES_CONTROL_FAILED));
                    }
                }
            }
        });

        // Subscribe to the error event
        mHubConnection.error(new ErrorCallback() {
            @Override
            public void onError(Throwable error) {
                error.printStackTrace();
            }
        });

        // Subscribe to the connected event
        mHubConnection.connected(new Runnable() {

            @Override
            public void run() {
                Log.e("SignalRService", "CONNECTED");
                is_service_connected = true;
                Log.e("Tag" , "is_service_connected-connected");
            }
        });

        // Subscribe to the closed event
        mHubConnection.closed(new Runnable() {

            @Override
            public void run() {
                Log.e("SignalRService", "DISCONNECTED");
                is_service_connected = false;
                Log.e("Tag" , "is_service_connected-closed");
            }
        });

        // Start the connection
        mHubConnection.start().done(new Action<Void>() {
            @Override
            public void run(Void aVoid) throws Exception {
                Log.e("SignalRService", "Done Connecting!");
            }
        });

        // Subscribe to the received event
        mHubConnection.received(new MessageReceivedHandler() {
            @Override
            public void onMessageReceived(JsonElement jsonElement) {
                Log.e("SignalRService", "RAW received message: " + jsonElement.toString());
            }
        });

    }


}

